package book;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedStreamTest {

	public static void main(String[] args) throws IOException {
		
		PipedOutputStream out = new PipedOutputStream();
		PipedInputStream in = new PipedInputStream(out);
		
		Thread p = new Thread(new PipedStreamProducer(out));
		Thread c = new Thread(new PipedStreamConsumer(in));
		
		p.start();
		c.start();
	}
}

class PipedStreamProducer implements Runnable{
	
	private PipedOutputStream out;
	
	public PipedStreamProducer(PipedOutputStream out){
		
		this.out = out;
	}
	
	@Override
	public void run() {

		for(int i = 0; i < 30; i++){
			
			try {
				out.write(i);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("生产" + i);
		}
	}
}

class PipedStreamConsumer implements Runnable{
	
	private PipedInputStream in;
	
	public PipedStreamConsumer(PipedInputStream in){
		
		this.in = in;
	}
	
	@Override
	public void run() {
		
		for(int i = 0; i < 30; i++){
			
			try {
				int result = in.read();
				System.out.println("消费" + result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
